<template>
  <!-- 用户收藏列表 -->
  <el-table :data="tableData" @row-dblclick="onRow" class="Table_box">
    <!-- 第一列 -->
    <el-table-column prop="imgAddress" label="封面" width="1" #default="one">
      <el-image style="width: 50px; height: 50px" :src="one.row.imgAddress" />
    </el-table-column>
    <!-- 第二列 -->
    <el-table-column prop="musicTitle" width="1" label="歌名"></el-table-column>
    <!-- 第三列 -->
    <el-table-column prop="singer" label="歌手" width="1"></el-table-column>
    <!-- 第四列 -->
    <el-table-column prop="star" width="1" label="收藏" #default="scope">
          <el-icon
            :color="star_color(scope.row.star)"
            @click="Favorite(scope.row)"
            size="25px"
          >
            <Star />
          </el-icon>
    </el-table-column>
  </el-table>
</template>
<script setup>
import { Star } from "@element-plus/icons-vue";
import { reactive, ref, computed, onMounted, watch } from "vue";
import musicListInfoStore from "../../stores/useMusicStore";
import userMsgInfoStore from "../../stores/useUserStore";
import { openInfo } from "../../utils/common";
import musicHttp from "../../api/musicHttp";
const musicStore = musicListInfoStore();
const userStore = userMsgInfoStore();
onMounted(() => {
  //获取数据
  UserFavoriteMusicList(userStore.userId, musicStore.search);
});
const tableData = reactive([]); //音乐列表

//user收藏夹 音乐列表/模糊查询
function UserFavoriteMusicList(userId, musicTitle) {
  tableData.splice(0, tableData.length); //清空数组
  musicHttp.getUserFavoriteMusicList(userId, musicTitle).then((res) => {
    tableData.push(...res.data);
  });
}
//双击某一行播放该音乐row是表格中该行的对象
function onRow(row) {
  //console.log("当前播放音乐id",row.musicId);
  musicStore.nowMusicId = row.musicId; //将id修改
}

//根据用户id音乐id收藏音乐
function addFavorite(id, musicId) {
  musicHttp.addFavorite(id, musicId).then((res) => {
    openInfo("", res.msg);
  });
}

//根据用户id音乐id取消收藏音乐
function removeFavorite(id, musicId) {
  musicHttp.removeFavorite(id, musicId).then((res) => {
    openInfo("", res.msg);
  });
}
//收藏与取消收藏
function Favorite(rowdata) {
  if (rowdata.star == false) {
    //如果状态是没有收藏则收藏并且修改状态为收藏
    addFavorite(userStore.userId, rowdata.musicId);
    rowdata.star = true;
  } else if (rowdata.star == true) {
    //如果状态是收藏则取消收藏并且修改状态为未收藏
    removeFavorite(userStore.userId, rowdata.musicId);
    rowdata.star = false;
  }
}
//收藏图标颜色变化
function star_color(star) {
  if (star) {
    return "aquamarine";
  } else {
    return "";
  }
}

// 搜索
const SE = computed(() => {
  return musicStore.search;
});

watch(SE, () => {
  if (SE.value != "") {
    UserFavoriteMusicList(userStore.userId, musicStore.search);
  } else {
    UserFavoriteMusicList(userStore.userId, musicStore.search);
  }
});
</script>

<style scoped>
.Table_box {
  width: 100%;
  height: 80vh;
}

.Table_box >>> .el-scrollbar__view,
.Table_box >>> .el-table__header,
.Table_box >>> .el-table__body {
  width: 100% !important;
}
</style>